#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @File : base_page.py
# @Autor: FY
# @Date: 2021/8/30

from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
import yaml
from selenium.webdriver.support.wait import WebDriverWait
from utils.common_function import get_projectDir


class BasePage:
    '''
    基类，所有page类的公共类
    '''

    _base_url = ""

    def __init__(self, driver: WebDriver = None):
        if driver == None:
            self.driver = webdriver.Chrome()
            self.driver.get(self._base_url)
        else:
            self.driver = driver

    def quit(self):
        self.driver.quit()

    def login(self):
        '''
        扫码登录函数，使用cookie登录
        :return: None
        '''
        cookies = []
        with open(get_projectDir() + "/cookies/cookies.yaml") as f:
            cookies = yaml.safe_load(f)

        for cookie in cookies:
            self.driver.add_cookie(cookie)

        self.driver.get(self._base_url)

    def find_element(self, by, value):
        if WebDriverWait(self.driver,10, 1).until(lambda x: self.driver.find_element(by, value)):
            return self.driver.find_element(by, value)
        else:
            return None

    def find_elements(self, by, value):
        '''
        Find elements given a By strategy and locator.
        :param by:
        :param value:
        :return: list of WebElement
        '''
        if WebDriverWait(self.driver,30, 1).until(lambda x: self.driver.find_elements(by, value)):
            return self.driver.find_elements(by, value)
        else:
            return []

    def click_element(self, by, value):
        '''
        点击页面元素
        :param by:
        :param value:
        :return None:
        '''
        if WebDriverWait(self.driver, 30, 1).until(lambda x: self.driver.find_element(by, value)):
            return self.driver.find_element(by, value).click()
        else:
            return None

    def add_text(self, by, value, *text):
        '''
        输入文本内容
        :param by:
        :param value:
        :param text:
        :return:
        '''
        if WebDriverWait(self.driver, 10, 1).until(lambda x: self.driver.find_element(by, value)):
            return self.driver.find_element(by, value).send_keys(text)
        else:
            return None

